<template>
  <a-modal :visible="visible" width="480px" title="编辑" cancelText="取消" okText="确定" @ok="handleEdit" @cancel="handleCancel">
    <DynamicForm :config="dyConfig" :questions="dyQuestions" class="dynamicForm" ref="dynamicForm"></DynamicForm>
  </a-modal>
</template>

<script lang="ts" setup>
import { DynamicForm } from '@/components/public-template';
import { Api, authorityManageSave, dataPermissionSave, generateCode, roleList, typeTree } from '@/config/api/dataAuthority';
import { message } from 'ant-design-vue';
import { onMounted, reactive, ref } from 'vue';
import { formInfoStore } from '@/store/modules/form';
import indexService from './addDialog.service';

const props = defineProps({
  // 模态框显隐
  visible: {
    type: Boolean,
    default: false
  },
  showType: {
    type: String,
    default: 'EDIT'
  },
  // 详情传数据
  data: {
    type: Object,
    default: () => {}
  },
  userIds: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(['update:visible', 'update:showType', 'refresh']);

const state = reactive({
  isDisabled: false, // 是否禁用
  showType: props.showType
});
// 弹窗标题
const dynamicForm = ref(null);

const formStore = formInfoStore();
formStore.setQuestions(indexService.getQuestions());
const dyQuestions = formStore.getQuestions;
const dyConfig: any = {
  queryUrl: state.showType === 'EDIT' ? Api.archiveFilePermissionGet : '',
  protType: state.showType === 'EDIT' ? 'get' : '',
  urlName: state.showType === 'EDIT' ? props.data.userId : '',
  noGetDataParams: state.showType === 'EDIT' ? true : false,
  cancelSave: true,
  grid: 24,
  layout: 'horizontal',
  beforeWithMethod(data) {
    // 如果详情数据是全部默认选择全部按钮, 再点自定义让用户自己选择不默认带出
    if (data.deptPerssiomId?.length === 1 && data.deptPerssiomId[0] === '0') {
      data.deptPerssiomId = [];
      return data;
    } else {
      dyQuestions[0].value = 1;
      dyQuestions[1].hidden = false;
    }
    for (let i of dyQuestions) {
      for (let j in data) {
        if (i.key === j) {
          i.value = data[j];
          if (!i.value && j == 'deptPerssiomId') {
            i.value = [];
          }
        }
      }
    }
  }
};

const handleCancel = () => {
  emit('update:visible', false);
};
// changeParams不支持传入数组ids, 暂时先自己处理额外数据
function findObjectById(arr, id) {
  for (let i = 0; i < arr.length; i++) {
    const obj = arr[i];
    if (obj.id === id) {
      return obj;
    }
    if (obj.childOrg && obj.childOrg.length > 0) {
      const foundObj = findObjectById(obj.childOrg, id);
      if (foundObj) {
        return foundObj;
      }
    }
  }
  return null;
}
const handleEdit = () => {
  const { deptId, deptName } = props.data;
  const userId = props.showType === 'EDIT' ? props.data?.userId : props.userIds;
  let params = { deptId, deptName, userId };
  if (!Array.isArray(params.userId)) {
    params.userId = [params.userId];
  }
  const dataForm = dynamicForm.value.getDataFrom();
  if (dataForm.dataPermission) {
    let list = [];
    Array.isArray(dataForm.deptPerssiomId) &&
      dataForm.deptPerssiomId.forEach((item) => {
        let obj = findObjectById(dyQuestions[1].options, item);
        list.push({ deptPerssiomName: obj.name, deptPerssiomid: obj.id });
      });
    params['list'] = list;
  } else {
    params['list'] = [{ deptPerssiomName: '全部', deptPerssiomid: 0 }];
  }
  dataPermissionSave(params).then((res) => {
    if (res.success) {
      message.success('编辑成功');
      emit('refresh');
      emit('update:visible', false);
    }
  });
};
</script>

<style lang="less" scoped>
.horizontalLayout {
  min-height: 60vh;
  .dynamicForm {
    flex-basis: 50%;
  }
  .form-tree-container {
    display: flex;
    border-radius: 6px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    flex: 1;
    .left {
      flex: 1;
      padding: 10px;
      border-right: 1px solid rgba(0, 0, 0, 0.15);
    }
    .right {
      flex: 1;
      padding: 10px;
    }
  }
}

.collapse {
  display: block;
  color: #333;
  font-weight: 500;
  font-size: 16px;
  margin-bottom: 5px;
}
.title-required::before {
  display: inline-block;
  margin-right: 4px;
  color: #ff4d4f;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
.security-check {
  margin-left: 23.5px;
  .ant-row {
    margin-bottom: 5px;
  }
}
.opt-check {
  .ant-row {
    margin-bottom: 5px;
  }
}

.footer-buttonGroups {
  display: flex;
  justify-content: center;

  & > button:not(:first-child) {
    margin-left: 20px;
  }
}
</style>
